
import logging
from trytond.transaction import Transaction
from trytond.pool import Pool
import calendar

def create_sequence(name, code, prefix, company, is_strict=True):
    if is_strict:
        obj_sequence = Pool().get('ir.sequence.strict')
    else:
        obj_sequence = Pool().get('ir.sequence')

    seq = obj_sequence()
    seq.name = name
    seq.code = code
    seq.padding = 6
    seq.company = company
    seq.prefix = prefix
    seq.type = 'incremental'
    seq.save()

    return seq

def create_config(model_name, field_name, sequence):
    config_obj = Pool().get(model_name)
    config_obj.write(1, {field_name : sequence.id})

def get_res_id(name, model=''):
    obj_data = Pool().get('ir.model.data')

    data = []
    i = name.find('.')
    if (i < 0):
        data.append(('fs_id','=',name))
    else:
        module = name[:i]
        n = name[i+1:]
        data.append(('fs_id','=',name[i+1:]))
        data.append(('module','=',name[:i]))

    if model != '':
        data.append(('model','=',model))

    data_id = obj_data.search(data)
    if not data_id:
        return None
        
    res = obj_data.browse(data_id)

    return res[0].db_id

def new_pcw_fiscalyear(company, company_prefix, year):
    company_prefix = company_prefix + year

    acc_move_seq = create_sequence('ACCOUNT MOVE', 'account.move', 'ACC-' + company_prefix + '-', company, False)
    customer_invoice_seq = create_sequence('SALE INVOICE', 'account.invoice', 'SIN-' + company_prefix + '-', company)
    customer_nc_seq = create_sequence('SALE CREDIT NOTE', 'account.invoice', 'SCN-' + company_prefix + '-', company)
    supplier_invoice_seq = create_sequence('PURCHASE INVOICE', 'account.invoice', 'PIN-' + company_prefix + '-', company)
    supplier_nc_seq = create_sequence('PURCHASE CREDIT NOTE', 'account.invoice', 'PCN-' + company_prefix + '-', company)

    obj_fiscal_year = Pool().get('account.fiscalyear')
    obj_fiscal_period = Pool().get('account.period')

    fy = obj_fiscal_year()
    fy.name = 'Fiscal Year '+ year
    fy.code = 'FY'+ year
    fy.start_date = year +'-01-01'
    fy.end_date = year +'-12-31'
    fy.company = company
    fy.post_move_sequence = acc_move_seq
    fy.out_invoice_sequence = customer_invoice_seq
    fy.out_credit_note_sequence = customer_nc_seq
    fy.in_invoice_sequence = supplier_invoice_seq
    fy.in_credit_note_sequence = supplier_nc_seq
    fy.save()

    vals_period={} 
    months = (1,2,3,4,5,6,7,8,9,10,11,12)

    year_int = int(year)

    for m in months:
        end_day = calendar.monthrange(year_int,m)
        str_end_day = str(end_day[1])
        str_month = '0' + str(m)            
        if m > 9: 
            str_month = str(m)
        
        period = obj_fiscal_period()
        period.name = str_month + year
        period.code = str_month + year
        period.fiscalyear = fy
        period.start_date = year +'-' + str_month + '-01'
        period.end_date = year +'-' + str_month + '-' + str_end_day
        period.save()

    return fy

def new_pcw_journal_sequence(journal, company, prefix):
    journal_seq = create_sequence(journal.name, 'account.journal', 
                    journal.code + '-' + prefix + '-', company, False)

    create_property('account.journal,' + str(journal.id), 'ir.sequence,' + str(journal_seq.id), 'sequence', 'ir.sequence', company)


def create_property(res, value, field_name, relation, company):
    property_obj = Pool().get('ir.property')
    field_obj = Pool().get('ir.model.field')

    prop = property_obj()
    prop.res = res
    prop.value = value
    prop.field = field_obj.search([('name', '=', field_name), ('relation', '=', relation)])[0]
    prop.company = company
    prop.save()
    return prop


def new_pcw_cash_bank(company, default_acc_code, journal=None, journal_name=None, journal_code=None, seq_prefix=None):
    if not journal:
        if not journal_name or not journal_code:
            raise ValueError("Journal name and code are requiered.") 
        journal_obj = Pool().get('account.journal')
        journal = journal_obj()
        journal.name = journal_name
        journal.code = journal_code
        journal.type = 'cash'
        journal.save()
        new_pcw_journal_sequence(journal, company, seq_prefix)
    
    if journal.type != 'cash':
        raise ValueError("Journal type must be 'cash'") 
    if not default_acc_code:
        raise ValueError("Default account code is requiered.") 

    account_obj = Pool().get('account.account')
    acc = account_obj.browse(account_obj.search([('code', '=', default_acc_code), ('company', '=', company.id)]))[0]
    create_property('account.journal,' + str(journal.id), 'account.account,' + str(acc.id), 'credit_account', 'account.account', company)
    create_property('account.journal,' + str(journal.id), 'account.account,' + str(acc.id), 'debit_account', 'account.account', company)

    return journal




